﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.Util;
using Emgu.CV.UI;
using System.Windows.Forms;
using CCWin;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;


namespace TY_75Stability.WinApp
{

    public class CVCamera
    {
        private VideoCapture capture;
        private VideoWriter videoWriter;
        private bool isStart = false;
        private bool isStartRecord = false;
        private string cameraPath = "";
        public CVCamera(string _cameraPath)
        {
            cameraPath = _cameraPath;
            this.capture = new VideoCapture(_cameraPath);
            this.capture.SetCaptureProperty(Emgu.CV.CvEnum.CapProp.Exposure, -7);
        }

        /// <summary>
        /// 停止摄像头
        /// </summary>
        public void Stop()
        {
            this.isStart = false;
        }

        /// <summary>
        /// 启动摄像头
        /// </summary>
        /// <param name="pb"></param>
        public void Start(PictureBox pb)
        {
            this.isStart = true;
            Task.Factory.StartNew(new Action(() =>
            {
                while (this.isStart)
                {
                    try
                    {
                        Stopwatch sw = new Stopwatch();
                        sw.Start();
                        //获取图像帧
                        Image<Bgr, byte> frame = this.capture.QueryFrame().ToImage<Bgr, byte>();

                        //对帧添加时间
                        CvInvoke.PutText(frame, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), new System.Drawing.Point(430, 20), Emgu.CV.CvEnum.FontFace.HersheyPlain, 1, new MCvScalar(255, 255, 0), 1);
                        sw.Stop();
                        //var fps = decimal.Round((decimal)(1000 / sw.Elapsed.TotalMilliseconds), 2);
                        //CvInvoke.PutText(frame, fps.ToString(), new System.Drawing.Point(20, 20), Emgu.CV.CvEnum.FontFace.HersheyPlain, 1, new MCvScalar(255, 255, 0), 1);
                        //判断是否记录视频
                        if (this.isStartRecord)
                            videoWriter.Write(frame.Mat);
                        if (frame != null)
                        {
                            using (Bitmap im = frame.Clone().ToBitmap())
                            {
                                //im.RotateFlip(RotateFlipType.Rotate180FlipNone);

                                Bitmap tempBitmap = im.Clone(new RectangleF(0, 0, im.Width, im.Height), PixelFormat.Format24bppRgb);

                                this.setPictureBoxControlImage(pb, new Bitmap(tempBitmap));
                                tempBitmap.Dispose();

                            }
                        }

                        frame.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Thread.Sleep(15000);
                        this.capture = new VideoCapture(cameraPath);
                    }
                }
            }));
        }

        /// <summary>
        /// 开始记录视频
        /// </summary>
        public void StartRecord(string fileName)
        {
            try
            {

                if (videoWriter == null)
                {
                    videoWriter = new VideoWriter(fileName, VideoWriter.Fourcc('M', 'P', '4', '2'), 22,
                        new Size(640, 480), true);
                    videoWriter.Set(VideoWriter.WriterProperty.Quality, 0.1);
                    this.isStartRecord = true;
                }

            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 停止记录视频
        /// </summary>
        public void StopRecord()
        {
            try
            {

                this.isStartRecord = false;
                if (videoWriter != null)
                {
                    //videoWriter.Dispose();
                    videoWriter = null;
                }

            }
            catch (Exception)
            {

                throw;
            }
        }
        //多线程设置PictureBox的图像
        private void setPictureBoxControlImage(PictureBox control, Bitmap value)
        {
            control.Invoke(new Action<PictureBox, Bitmap>((ct, v) => { ct.Image = v; }), new object[] { control, value });
        }
    }
}
